package com.lagou.demo.controller;


import com.lagou.demo.feign.EmailServiceI;
import com.lagou.demo.pojo.Code;
import com.lagou.demo.service.ICodeService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;

@RestController
@RequestMapping("code")
public class CodeController {

    @Autowired
    private ICodeService codeService;

    @Autowired
    private EmailServiceI emailService ;


    @PostMapping("/create/{email}")
    public Boolean newCode(@PathVariable("email") String email) {
        Code code = new Code();
        String codeStr = "";
        for (int i = 0; i < 6; i++) {
            codeStr += new Random().nextInt(10);
        }
        code.setCode(codeStr);
        code.setEmail(email);
        code.setCreatetime(new Date());
        code.setExpiretime(DateUtils.addMinutes(new Date(), 10));
        // todo 发送邮件
        emailService.sendEmail(email, "您的验证码为：" + codeStr);
        try {
            codeService.insert(code);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 校验验证码是否正确， 0正确1错误2超时
    @PostMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable("email") String email, @PathVariable("code") String code) {
        Code cd = new Code();
        cd.setEmail(email);
        try {
            Code one = codeService.findOne(cd);
            if (one.getExpiretime().getTime() - new Date().getTime() < 0) {
                return 2;
            }
            if (one.getCode().equals(code)) {
                return 0;
            } else {
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

}
